package  
{
  import flash.display.Sprite;
  import flash.events.Event;
  import flash.geom.Point;
	/**
   * ...
   * @author Ivan
   */
  public class Army extends Sprite
  {
    
    public function Army() 
    {
      addEventListener(Event.ENTER_FRAME, onEnterFrame);
      addEventListener(Event.REMOVED_FROM_STAGE, onRemoveFromStage);
    }
    
    private function onRemoveFromStage(e:Event):void
    {
      removeEventListener(Event.ENTER_FRAME, onEnterFrame);
      removeEventListener(Event.REMOVED_FROM_STAGE, onRemoveFromStage);
    }
    
    private function onEnterFrame(e:Event):void
    {
      if (!target) return;
      
      var unit_speed:Number = 2;
      
      var p1:Point = new Point(x, y);
      var p2:Point = new Point(target.x, target.y);
      var dir:Point = p2.subtract(p1);
      
      if (p1.subtract(p2).length < 5)
      {
        // Target reached
        if (target.owner == owner || target.owner == null)
        {
          target.population += numSoldiers;
          target.owner = owner;
        }
        else
        {
          // Invading occupied by enemy city
          var casualties:Number = Math.min(target.population, numSoldiers);
          target.population -= casualties;
          numSoldiers -= casualties;
          if (target.population <= 0)
          {
            // win
            target.population = numSoldiers;
            target.owner = owner;
          }
          if (numSoldiers <= 0)
          {
            // lose
            // Army will be lose.
          }
          
        }
        
        if (target.population > target.populationLimit)
            target.population = target.populationLimit;
        
        removeEventListener(Event.ENTER_FRAME, onEnterFrame);
        parent.removeChild(this);
        return;
      }
      
      // Move unit
      dir.normalize(unit_speed);      
      x += dir.x;
      y += dir.y;
      
      draw();      
    }
    
    private function draw():void
    {
      graphics.clear();
      graphics.lineStyle(0);
      graphics.beginFill(owner.color);
      graphics.drawCircle(0, 0, 1 + numSoldiers/2);
      graphics.endFill();
    }
    
    public var numSoldiers:int;
    public var target:Town;
    public var owner:Player;
    
  }

}